package com.bikes.mileagetracker.persistence

import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.bikes.mileagetracker.MileageTrackerApplication
import com.bikes.mileagetracker.orm.BaseDataBaseHelper
import com.bikes.mileagetracker.entity.UserEntity
import com.bikes.mileagetracker.service.IPersistenceService
import com.bikes.mileagetracker.service.PersistenceService
import com.bikes.mileagetracker.utils.SharedPreferencesUtils
import com.bikes.mileagetracker.utils.TaskUtils
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith


@RunWith(AndroidJUnit4::class)
class LatestUserTest {

    val USERS = listOf<UserEntity>(
            UserEntity().apply {
                username = "wangds"
                status = 0
            },
            UserEntity().apply {
                username = "wujingc"
                status = 0
            },
            UserEntity().apply {
                username = "zhengw"
                status = 0
            },
            UserEntity().apply {
                username = "wangyt"
                status = 0
            }
    )

    val LOCK = Object()

    fun notifyLock() {
        synchronized(LOCK) {
            LOCK.notify()
        }
    }

    fun lock() {
        synchronized(LOCK) {
            LOCK.wait(60000)
        }
    }

    @Test
    fun test() {

        val appContext = InstrumentationRegistry.getTargetContext()
        Assert.assertEquals("com.bikes.mileagetracker", appContext.packageName)


        BaseDataBaseHelper.createTable(BaseDataBaseHelper.getDatabase(), UserEntity::class.java, true)

        val helper = object : BaseDataBaseHelper<UserEntity>() {}

        while (PersistenceService.service == null) {
            PersistenceService.bind(appContext)
            Thread.sleep(100)
        }

        val service = PersistenceService.service!!


        SharedPreferencesUtils.putStringPrivateA(MileageTrackerApplication.getCurrentApplication(),
                IPersistenceService.SHARED_PREFERENCES_NAME_USER,
                IPersistenceService.SHARED_PREFERENCES_KEY_LATEST,
                null
        )

        USERS.forEach { entity ->
            TaskUtils.runInBackground {
                service.saveUser(entity)
                notifyLock()
            }
            lock()

            var result = helper.byId(entity.id)
            Assert.assertNotNull(result)
            Assert.assertNotNull(result!!.id)
        }

        var lu = service.loadLatestUser()
        Assert.assertEquals(lu?.id?:"", "")
        lu = USERS[1]
        service.updateLatestUser(lu)
        lu = service.loadLatestUser()
        Assert.assertEquals(lu?.id?:"", USERS[1].id)


        helper.delete(USERS[0])
        helper.delete(USERS[1])
        helper.delete(USERS[2])
        helper.delete(USERS[3])

    }
}